import * as EXIF from 'exif-js'

export class ImageProcessor implements IImageProcessor {


  autoZoomAndRotateFromUrl(url: string, ratio: number, callback: any): any {

    if (!url) {
      return;
    }

    let reader = new FileReader();
    let image = new Image();
    let orientation = 1;

    // 监听读取完成事件
    reader.onload = (readerEvent: any) => {
      image.src = readerEvent.target.result;
      image.onload = () => {
        callback(this.getDataFromCanvas(image, ratio, orientation));
      }
    };

    // 读取图片
    this.getImageBlob(url,
      (blob) => {
        EXIF.getData(blob, function () {
          orientation = EXIF.getTag(this, 'Orientation');
          reader.readAsDataURL(blob);
        });
      });
  }

  autoZoomAndRotateFromFile(file: any, ratio: number, callback: any): any {

    if (!file) {
      return;
    }

    EXIF.getData(file, () => {
      let orientation = EXIF.getTag(file, 'Orientation');
      console.log(orientation);

      let reader = new FileReader();
      let image = new Image();
      // 监听读取完成事件
      reader.onload = (readerEvent: any) => {
        image.src = readerEvent.target.result;
        image.onload = () => {
          callback(this.getDataFromCanvas(image, ratio, orientation));
        }
      };
      // 读取图片
      reader.readAsDataURL(file);
    });
  }


  getImageBlob(url, callback) {
    let xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'blob';
    xhr.onload = () => {
      if (xhr.status == 200) {
        if (callback) {
          callback(xhr.response);
        }
      }
    };
    xhr.send();
  }

  getDataFromCanvas(image: any, ratio: number, orientation: number): string {
    let dstWidth = Math.ceil(image.width * ratio);
    let dstHeight = Math.ceil(image.height * ratio);

    let canvas = document.createElement('canvas');
    console.log('width: ' + image.width);
    console.log('height: ' + image.height);

    canvas.width = dstWidth;
    canvas.height = dstHeight; //计算等比缩小后图片宽高

    let ctx = canvas.getContext('2d');

    if(orientation && orientation != 1){
      switch(orientation){
        case 6:
          canvas.width = dstHeight;
          canvas.height = dstWidth;
          ctx.rotate(Math.PI / 2);
          ctx.drawImage(image, 0, -dstHeight, dstWidth, dstHeight);
          break;
        case 3:
          ctx.rotate(Math.PI);
          ctx.drawImage(image, -dstWidth, -dstHeight, dstWidth, dstHeight);
          break;
        case 8:
          canvas.width = dstHeight;
          canvas.height = dstWidth;
          ctx.rotate(3 * Math.PI / 2);
          ctx.drawImage(image, -dstWidth, 0, dstWidth, dstHeight);
          break;
      }
    }else{
      ctx.drawImage(image, 0, 0, dstWidth, dstHeight);
    }

    let imageData = canvas.toDataURL('image/jpeg', 1);

    return imageData;
  }
}
